<template>
  <el-dialog
    title="设备MQTT提交格式"
    :visible.sync="visible"
    width="80%"
    :before-close="handleClose"
    append-to-body
  >
    <div v-if="mqttData" class="mqtt-format-container">
      <!-- 设备信息 -->
      <el-card class="device-info-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="card-title">设备信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">设备名称：</span>
              <span class="value">{{ mqttData.deviceInfo.deviceName }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">设备类型：</span>
              <span class="value">{{ mqttData.deviceInfo.deviceType }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">能源类型：</span>
              <span class="value">{{ mqttData.deviceInfo.energyType }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">设备位置：</span>
              <span class="value">{{ mqttData.deviceInfo.location }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 格式选择 -->
      <el-card class="format-selector-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="card-title">数据格式选择</span>
        </div>
        <el-radio-group v-model="selectedFormat" @change="onFormatChange">
          <el-radio label="single">
            <span class="format-option">
              <strong>单设备格式</strong>
              <span class="format-desc">适用于单个设备实时数据上报</span>
            </span>
          </el-radio>
          <el-radio label="array">
            <span class="format-option">
              <strong>数组格式</strong>
              <span class="format-desc">适用于网关设备批量上报多个子设备数据</span>
            </span>
          </el-radio>
        </el-radio-group>
      </el-card>

      <!-- MQTT配置信息 -->
      <el-card class="mqtt-config-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="card-title">MQTT配置</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="config-item">
              <span class="label">主题 (Topic)：</span>
              <el-input
                v-model="currentTopic"
                readonly
                class="config-input"
              >
                <el-button
                  slot="append"
                  icon="el-icon-copy-document"
                  @click="copyToClipboard(currentTopic, '主题')"
                ></el-button>
              </el-input>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-item">
              <span class="label">QoS：</span>
              <el-input
                v-model="mqttData.qos"
                readonly
                class="config-input"
              ></el-input>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="selectedFormat === 'array'" :gutter="20" style="margin-top: 15px;">
          <el-col :span="24">
            <div class="config-item">
              <span class="label">说明：</span>
              <span class="format-note">数组格式推荐使用网关主题，可以一次发送多个设备数据</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- JSON格式 -->
      <el-card class="json-format-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="card-title">
            JSON数据格式
            <el-tag v-if="selectedFormat === 'single'" type="primary" size="mini">单设备</el-tag>
            <el-tag v-else type="success" size="mini">数组格式</el-tag>
          </span>
          <el-button
            style="float: right; padding: 3px 0"
            type="text"
            icon="el-icon-copy-document"
            @click="copyJsonToClipboard"
          >复制JSON</el-button>
        </div>
        <div class="json-container">
          <pre class="json-content">{{ formattedJson }}</pre>
        </div>
        <div v-if="selectedFormat === 'array'" class="array-info">
          <el-alert
            title="数组格式说明"
            type="info"
            :closable="false"
            show-icon
          >
            <div slot="default">
              <p>• 数组格式可以一次发送多个设备数据，提高传输效率</p>
              <p>• 每个数组元素都是一个完整的设备数据对象</p>
              <p>• 系统会自动使用批量插入，提高数据库写入性能</p>
              <p>• 适用于网关设备批量上报多个子设备数据的场景</p>
            </div>
          </el-alert>
        </div>
      </el-card>

      <!-- 字段说明 -->
      <el-card class="field-desc-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="card-title">字段说明</span>
        </div>
        <el-table
          :data="fieldDescriptionList"
          border
          size="small"
          max-height="300"
        >
          <el-table-column prop="field" label="字段名" width="150"></el-table-column>
          <el-table-column prop="description" label="说明"></el-table-column>
        </el-table>
      </el-card>

      <!-- 使用说明 -->
      <el-card class="usage-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="card-title">使用说明</span>
        </div>
        <div class="usage-content">
          <div v-if="selectedFormat === 'single'">
            <h4>单设备格式使用说明：</h4>
            <ol>
              <li>设备应按照上述JSON格式向指定主题发送数据</li>
              <li>deviceCode字段必须与系统中的设备编码完全一致</li>
              <li>timestamp字段使用毫秒级Unix时间戳</li>
              <li>根据设备的能源类型，只需要发送对应的字段</li>
              <li>status和quality字段用于设备状态和数据质量监控</li>
              <li>extend1、extend2、extend3为扩展字段，可用于传递额外信息</li>
            </ol>
          </div>
          <div v-else>
            <h4>数组格式使用说明：</h4>
            <ol>
              <li>网关设备可以一次发送多个设备数据，使用JSON数组格式</li>
              <li>每个数组元素都是一个完整的设备数据对象</li>
              <li>每个设备的deviceCode字段必须与系统中的设备编码完全一致</li>
              <li>推荐使用网关主题：<code>ems/gateway/{gatewayCode}/data</code></li>
              <li>系统会自动检测数组格式并进行批量处理</li>
              <li>批量处理可以提高数据传输和存储效率</li>
              <li>适用于网关设备管理多个子设备的场景</li>
            </ol>
          </div>
          <div class="topic-examples">
            <h4>支持的主题格式：</h4>
            <ul>
              <li><code>ems/device/{deviceCode}/data</code> - 单设备数据（支持数组格式）</li>
              <li><code>ems/sensor/{deviceCode}/data</code> - 传感器数据（支持数组格式）</li>
              <li><code>ems/energy/{deviceCode}/data</code> - 能耗数据（支持数组格式）</li>
              <li><code>ems/gateway/{gatewayCode}/data</code> - 网关批量数据（推荐数组格式）</li>
            </ul>
          </div>
        </div>
      </el-card>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关 闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "MqttFormatDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    mqttData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      selectedFormat: 'single' // 默认选择单设备格式
    };
  },
  computed: {
    formattedJson() {
      if (!this.mqttData || !this.mqttData.payload) {
        return '';
      }

      if (this.selectedFormat === 'array') {
        // 生成数组格式，包含当前设备和示例设备
        const arrayData = [
          this.mqttData.payload,
          this.generateExampleDevice('DEV002'),
          this.generateExampleDevice('SENSOR001')
        ];
        return JSON.stringify(arrayData, null, 2);
      } else {
        return JSON.stringify(this.mqttData.payload, null, 2);
      }
    },
    currentTopic() {
      if (!this.mqttData) {
        return '';
      }

      if (this.selectedFormat === 'array') {
        // 数组格式使用网关主题
        return 'ems/gateway/GATEWAY_001/data';
      } else {
        return this.mqttData.topic;
      }
    },
    fieldDescriptionList() {
      if (!this.mqttData || !this.mqttData.fieldDescriptions) {
        return [];
      }
      return Object.entries(this.mqttData.fieldDescriptions).map(([field, description]) => ({
        field,
        description
      }));
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false);
    },
    onFormatChange(format) {
      this.selectedFormat = format;
    },
    generateExampleDevice(deviceCode) {
      // 生成示例设备数据
      const baseData = {
        deviceCode: deviceCode,
        timestamp: Date.now(),
        status: "0",
        quality: "0"
      };

      if (deviceCode.startsWith('DEV')) {
        // 电力设备示例
        return {
          ...baseData,
          power: Math.round((Math.random() * 1000 + 500) * 100) / 100,
          totalEnergy: Math.round((Math.random() * 5000 + 3000) * 100) / 100,
          voltage: Math.round((Math.random() * 10 + 215) * 10) / 10,
          current: Math.round((Math.random() * 5 + 3) * 100) / 100,
          powerFactor: Math.round((Math.random() * 0.1 + 0.9) * 1000) / 1000,
          extend1: `设备位置:${deviceCode}车间`,
          extend2: "设备类型:电力设备",
          extend3: `设备名称:${deviceCode}`
        };
      } else if (deviceCode.startsWith('SENSOR')) {
        // 传感器设备示例
        return {
          ...baseData,
          temperature: Math.round((Math.random() * 10 + 20) * 10) / 10,
          humidity: Math.round((Math.random() * 30 + 50) * 10) / 10,
          pressure: Math.round((Math.random() * 2 + 1) * 100) / 100,
          extend1: `设备位置:${deviceCode}区域`,
          extend2: "设备类型:环境传感器",
          extend3: `设备名称:${deviceCode}`
        };
      } else {
        // 默认设备
        return {
          ...baseData,
          power: 100.0,
          extend1: `设备位置:${deviceCode}区域`,
          extend2: "设备类型:其他设备",
          extend3: `设备名称:${deviceCode}`
        };
      }
    },
    copyToClipboard(text, type) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success(`${type}已复制到剪贴板`);
        }).catch(() => {
          this.fallbackCopyTextToClipboard(text, type);
        });
      } else {
        this.fallbackCopyTextToClipboard(text, type);
      }
    },
    copyJsonToClipboard() {
      this.copyToClipboard(this.formattedJson, 'JSON格式');
    },
    fallbackCopyTextToClipboard(text, type) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.top = "0";
      textArea.style.left = "0";
      textArea.style.position = "fixed";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand('copy');
        this.$message.success(`${type}已复制到剪贴板`);
      } catch (err) {
        this.$message.error('复制失败，请手动复制');
      }
      document.body.removeChild(textArea);
    }
  }
};
</script>

<style scoped>
.mqtt-format-container {
  max-height: 70vh;
  overflow-y: auto;
}

.device-info-card,
.format-selector-card,
.mqtt-config-card,
.json-format-card,
.field-desc-card,
.usage-card {
  margin-bottom: 20px;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.info-item,
.config-item {
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
  color: #606266;
}

.value {
  color: #303133;
}

.config-input {
  margin-top: 5px;
}

.json-container {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.json-content {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.usage-content {
  color: #606266;
  line-height: 1.8;
}

.usage-content ol {
  padding-left: 20px;
}

.usage-content li {
  margin-bottom: 8px;
}

/* 格式选择器样式 */
.format-option {
  display: flex;
  flex-direction: column;
  margin-left: 8px;
}

.format-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.format-note {
  color: #909399;
  font-size: 13px;
}

/* 数组格式信息样式 */
.array-info {
  margin-top: 15px;
}

.array-info .el-alert {
  border-radius: 4px;
}

.array-info p {
  margin: 5px 0;
  font-size: 13px;
}

/* 主题示例样式 */
.topic-examples {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.topic-examples h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.topic-examples ul {
  margin: 0;
  padding-left: 20px;
}

.topic-examples li {
  margin-bottom: 5px;
  font-size: 13px;
}

.topic-examples code {
  background-color: #e6effb;
  color: #409eff;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
}
</style>
